<template>
  <div class="body_bgi full relative p_10">
    <bigscreen-header headerName="谱系档案" />

    <div class="w_full h_full-50 flex_row_between" v-if="isStart">
    <!-- <div class="w_full h_full-100 flex_row_between p_10"> -->

      <!-- rfids -->
      <div class="w_360 h_full scroll_box overflow_y_auto chart_box_bgi_1 p_10 border_box">
        <div class="w_full h_30 lh_30 color_fff fw_bold text_center"> 扫描羊 RFID 信息</div>
        <div class="w_full h_full-30 scroll_box overflow_y_auto color_fff">
          <div 
            class="w_full h_40 lh_40 fs_20 cursor"
            :class="activeIndex == index ? 'main_color border_b_1_s_main_color' : 'color_fff'"
            v-for="(rfid, index) in rfidList" :key="index" @click="clickRfid(rfid, index)">
            {{ formatIndex(index) + '. ' + rfid }}
          </div>
        </div>
      </div>

      <div class="w_full-360 h_full flex_row_start chart_box_bgi_1">
        <div class="w_250 h_full p_10" v-if="activeIndex !== null">
          <!-- 当前羊基本信息 -->
          <div class="w_full h_50_p scroll_box overflow_y_auto">
            <div class="w_full h_30 flex_row_between flex_center">
              <div class="h_30 main_color fw_bold fs_16 ls_2 flex_row_start flex_center fw_bold">
                <div class="w_1 h_15 main_bgc main_border mr_10"></div>当前羊
              </div>
              <div class="main_color fs_14">羊编号：{{ sheepInfo.id }}</div>
            </div>

            <div class="w_full h_full-30 color_fff fs_20 scroll_box overflow_y_auto" v-if="sheepInfo.id">
              <!-- <div class="w_full main_color fs_20 fw_bold">RFID: {{ sheepInfo.rfid }}</div> -->
              <div class="w_full color_fff">{{ sheepInfo.farmName }}</div>

              <div class="w_full h_full-70 flex_row_start color_fff mt_10">
                <div class="full ph_5">
                  <div class="full chart_box_bgi_2 border_radius_10 p_10 y_scroll overflow_y_auto">
                    <div class="w_full flex_row_between"><div class="color_8B8F98">身高:</div><div class="color_ccc">{{ sheepInfo.height }} cm</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">体长:</div><div class="color_ccc">{{ sheepInfo.tiLength }} cm</div> </div>
                    <!-- <div class="w_full flex_row_between"><div class="color_8B8F98">等级:</div><div class="color_ccc">{{ formatLevel(sheepInfo.leaveType) }}</div></div> -->
                    <div class="w_full flex_row_between"><div class="color_8B8F98">胸围:</div><div class="color_ccc">{{ sheepInfo.chest }} cm</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">产毛量:</div><div class="color_ccc">{{ sheepInfo.maoCount }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">净重:</div><div class="color_ccc">{{ sheepInfo.netWeight }} kg</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">头毛:</div><div class="color_ccc">{{ sheepInfo.touMao }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">类型与皱褶:</div><div class="color_ccc">{{ sheepInfo.wrinkling }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">毛长度:</div><div class="color_ccc">{{ sheepInfo.maoLength }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">密度:</div><div class="color_ccc">{{ sheepInfo.density }} </div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">弯曲度:</div><div class="color_ccc">{{ sheepInfo.wanQu }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">细度:</div><div class="color_ccc">{{ sheepInfo.xiDu }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">油汗:</div><div class="color_ccc">{{ sheepInfo.oilSweat }}</div></div>
                    <div class="w_full flex_row_between"><div class="color_8B8F98">均匀度:</div><div class="color_ccc">{{ sheepInfo.uniformity }}</div></div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 祖先羊 基本信息 -->
          <div class="w_full h_50_p">
            <div class="w_full h_30 flex_row_between flex_center">
              <div class="h_30 main_color fw_bold fs_16 ls_2 flex_row_start flex_center fw_bold">
                <div class="w_1 h_15 main_bgc main_border mr_10"></div>祖先羊
              </div>
              <div class="main_color fs_14" v-if="sheepInfo2.id">羊编号：{{ sheepInfo2.id }}</div>
            </div>

            <div class="w_full h_full-30 color_fff fs_20" v-if="sheepInfo2.id">
              <div class="full">
                <!-- <div class="w_full main_color fs_20 fw_bold">RFID: {{ sheepInfo2.rfid }}</div> -->
                <div class="w_full color_fff">{{ sheepInfo2.farmName }}</div>

                <div class="w_full h_full-70 flex_row_start color_fff mt_10">
                  <div class="full ph_5">
                    <div class="full chart_box_bgi_2 border_radius_10 p_10 y_scroll overflow_y_auto">
                      <div class="w_full flex_row_between"><div class="color_8B8F98">身高:</div><div class="color_ccc">{{ sheepInfo2.height }} cm</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">体长:</div><div class="color_ccc">{{ sheepInfo2.tiLength }} cm</div> </div>
                      <!-- <div class="w_full flex_row_between"><div class="color_8B8F98">等级:</div><div class="color_ccc">{{ formatLevel(sheepInfo2.leaveType) }}</div></div> -->
                      <div class="w_full flex_row_between"><div class="color_8B8F98">胸围:</div><div class="color_ccc">{{ sheepInfo2.chest }} cm</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">产毛量:</div><div class="color_ccc">{{ sheepInfo2.maoCount }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">净重:</div><div class="color_ccc">{{ sheepInfo2.netWeight }} kg</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">头毛:</div><div class="color_ccc">{{ sheepInfo2.touMao }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">类型与皱褶:</div><div class="color_ccc">{{ sheepInfo2.wrinkling }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">毛长度:</div><div class="color_ccc">{{ sheepInfo2.maoLength }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">密度:</div><div class="color_ccc">{{ sheepInfo2.density }} </div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">弯曲度:</div><div class="color_ccc">{{ sheepInfo2.wanQu }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">细度:</div><div class="color_ccc">{{ sheepInfo2.xiDu }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">油汗:</div><div class="color_ccc">{{ sheepInfo2.oilSweat }}</div></div>
                      <div class="w_full flex_row_between"><div class="color_8B8F98">均匀度:</div><div class="color_ccc">{{ sheepInfo2.uniformity }}</div></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="w_full-250 h_full">
          <sheep-tree :chartData="chartData" @clickSheep="clickSheep" />
        </div>
      </div>
    </div>

    <div class="w_full h_full-100 p_10 relative" v-if="!isStart">
      <div class="w_full h_170 absolute_center">
        <div class="w_120 h_120 absolute left_center top_0">
          <img class="full" src="../assets/images/icon/手持设备@2x.png" alt="">
        </div>

        <div class="w_full text_center main_color absolute left_center bottom_0 fs_30 ls_2">请在手持设备上扫描RFID</div>
      </div>
    </div>
  </div>
</template>

<script>
  import BigscreenHeader from '@/common/Header.vue'
  import SheepTree from '@/common/SheepTree.vue'
  import { 
    getCattleInfo,
    getSheepPedigree,
    currentSheepList
  } from '@/api/sheep/index.js'

  import ws2 from "@/util/websocket2"

  export default {
    name: 'PuXi',
    components: { BigscreenHeader, SheepTree },
    data() {
      return {
        webSctMsg: null,
        webSctState: null,

        rfidList: [],

        activeIndex: null,

        sheepInfo: {},
        sheepInfo2: {},

        chartData: {},

        relationMap: {
          isFatherOf: '父',
          isMotherOf: '母',
          Cattle: 'Cattle'
        },

        isStart: sessionStorage.getItem('isStart') || false,
        sheep_rfid: '',
      }
    },
    
    async mounted() {
      // 获取 房间中的 当前羊
      this.currentSheepList(1000)

      var websocket_state = window.sessionStorage.getItem('websocket_state')
      if (!websocket_state || websocket_state != 1) {
        // 获取 token 的手机号 是 ：自定义的手机号
        let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc1JlZnJlc2giOmZhbHNlLCJpZCI6MTgsImlhdCI6MTcyNjEzMTM3MiwiZXhwIjoxNzMzOTA3MzcyfQ.G1z5Fp3DRVxnUXAAAXh5zqjmexHdEGdKHgGVV33lsxE'
        let roomId = 1000

        if (token && roomId) {
          // 链接 webSocket
          this.connectWebSocket(token, roomId)       
        } else {
          console.log('weocsecket 缺少链接参数！');
        }
      }   

      window.addEventListener('beforeunload', e => {
        console.log('浏览器将要刷新');

        // 断开 websocket 链接 状态
        window.sessionStorage.setItem('websocket_state', 2)
      })
    },
    methods: {
      // 链接 webSocket 
      connectWebSocket(token, roomId) {
        ws2.init(
          `wss://xmy.5mus.com/api/ws?token=${token}&roomId=${roomId}`,
          this.token,
          data => {
            try {
              var msg = JSON.parse(data)

              this.webSctMsg = msg

              // 获取 扫码枪 扫描后的 信息 =>  SheepEntity：单只羊; SheepRfids: 多只羊
              if (msg.type == 'SheepRfids') {
                if (msg.data.rfids && msg.data.rfids.length) {
                  this.isStart = true
                  sessionStorage.setItem('isStart', true)
                  // this.activeIndex = 0
                  // this.rfidList = msg.data.rfids

                  // 默认获取 第一个 羊的 基本信息、 谱系档案
                  // this.getCattleInfo(msg.data.rfids[0])

                  let arr = msg.data.rfids.filter(item => !this.rfidList.includes(item))

                  this.rfidList = [...this.rfidList, ...arr]
                } else {
                  // 清空 rfidList
                  this.rfidList = []

                  this.sheepInfo = {}
                  this.sheepInfo2 = {}
                  this.chartData = {}
                }
              }
            } catch (err) {
              this.$message.error(err)
            }
          },
          state => {
            console.log("state changed !");

            this.webSctState = state
          }
        )

        window.sessionStorage.setItem('sock', ws2.wsObj)
      },

      // 页面刷新时 
      async currentSheepList(roomId) {
        let res = await currentSheepList(roomId)
        try {
          if (res.code == 1000) {
            this.rfidList = res.data.rfids
            
            // this.getCattleInfo(res.data.rfids[0])
          }
        } catch(err) {
          console.log('获取羊的养殖档案详情失败 : ', err)
        }
      },

      // 获取 羊的 养殖档案详情
      async getCattleInfo(rfid) {
        this.chartData = {}
        let res = await getCattleInfo(rfid)
        try {
          if (res.code == 200) {
            if (res.data !== null && res.data.id) {
              this.sheepInfo = res.data
              // 获取 羊的 谱系档案
              this.getSheepPedigree(res.data.id)
            } else {
              this.sheepInfo = {}

              this.chartData = {
                nodes: [],
                edges: []
              }
            }
          }
        } catch(err) {
          console.log('获取羊的养殖档案详情失败 : ', err)
        }
      },

      // 获取 羊的 谱系档案
      async getSheepPedigree(sheep_id) {
        let res = await getSheepPedigree(sheep_id)
        try {
          if (res.code == 200) {
            let nodes = []
            let edges = []

            for (let i in res.data.graph.nodes) {
              nodes.push({ 
                id: res.data.graph.nodes[i].id.toString(), 
                // label: this.relationMap[res.data.nodes[i].labels[0]], 
                label: `羊编号: ${res.data.graph.nodes[i].props.cattleId}`,
                props: res.data.graph.nodes[i].props, 
                // img: res.data.graph.nodes[i].props.imgList && res.data.graph.nodes[i].props.imgList.length 
                // ?  filePath + res.data.graph.nodes[i].props.imgList[0] : 'https://ts1.cn.mm.bing.net/th/id/R-C.0b97d47208b2b4003d43d96ca6882dae?rik=demLMuWG0ke7jA&riu=http%3a%2f%2fpic.616pic.com%2fys_img%2f00%2f42%2f63%2fd2CidQ1QH9.jpg&ehk=mTxRWP8t5C1vnAE7Im6CRBMYHW3yoZaTJzWKzRR33oE%3d&risl=&pid=ImgRaw&r=0'
                img: 'https://tse1-mm.cn.bing.net/th/id/OIP-C.7skvAoD2D87ajKk8tMoK3AAAAA?w=177&h=180&c=7&r=0&o=5&pid=1.7',
                type: 'rect-jsx',
                color: res.data.graph.nodes[i].props.sex == 0 ? '#2196f3' : '#f07c7c',
                sex: res.data.graph.nodes[i].props.sex == 0 ? '公' : '母',
                disc: this.formatDisc(res.data.graph.nodes[i])
              })
            }

            for (let j in res.data.graph.edges) {
              edges.push({ 
                source: res.data.graph.edges[j].dstId.toString(), 
                target: res.data.graph.edges[j].srcId.toString(), 
                // label: this.relationMap[res.data.graph.edges[j].label],
                style: {
                  startArrow: true
                },
                props: res.data.graph.edges[j].props
              })
            }

            this.chartData = {
              nodes,
              edges
            }
          }
        } catch(err) {
          console.log('获取羊的谱系档案失败 : ', err)
        }
      },

      // 点击 rfid
      clickRfid(rfid, index) {
        this.sheep_rfid = rfid
        this.activeIndex = index

        this.sheepInfo = {}
        this.sheepInfo2 = {}

        // 获取 基本信息
        this.getCattleInfo(rfid)
        // this.getCattleInfo('E2801191A00000001BB1F43C')
      },

      // 点击 谱系 中的羊
      async clickSheep(params) {
        // 获取 被点击的 羊的 数据
        let res = await getCattleInfo(params.rfid)
        try {
          if (res.code == 200) {
            setTimeout(() => { 
              this.sheepInfo2 = res.data 
            }, 500)
          }
        } catch(err) {
          console.log('获取羊的养殖档案详情失败 : ', err)
        }
      },

      formatAnimalGender(val) {
        return val == 0 ? '公' : '母' 
      },

      formatDisc(node_item) {
        let val = ''
        if (node_item.props.rfid == this.sheep_rfid) {
          val = '当前羊'
        // } else if (node_item.props.sex == 0) {
        //   val = '父亲'
        // } else if (node_item.props.sex == 1) {
        //   val = '母亲'
        } else {
          val = ''
        }

        return val
      },

      formatIndex(index) {
        let num = index + 1
        if (num < 10) {
          return '0' + num
        } else {
          return num
        }
      }

    }
  }
</script>

<style>
  .login_form_box { box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); padding: 20px 30px; }

  .login_form_box > .el-form  {
    background-color: var(--sub-color) !important;
  }

  .login_form_box > .el-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner {
    background-color: var(--sub-color) !important;
    color: var(--main-color);
    text-align: center !important;
    border: none !important;
  }

  .login_form_box > .el-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner:nth-child(1) {
    border-top-left-radius: 10px !important;
    border-top-right-radius: 10px !important;
  }

  .login_form_box > .el-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner:nth-child(2) {
    border-bottom-left-radius: 10px !important;
    border-bottom-right-radius: 10px !important;
  }

  /* 滚动条没有边框 */
.y_scroll::-webkit-scrollbar {
  width: 2px;
  height: 100%;
  background-color: #888;
}

::-webkit-scrollbar-thumb {                 /*表示纵向滚动块*/
  border-radius: 10px;
  background: #E4CFBB;
}
</style>